$(function(){
	var imgurl ="view/templates/style/images/";
	
	//******************************
	//*** Register formulär ***
	//******************************	
	
		$("#create_register_popup").click(function(event){ 
			var box = $("<div/>").attr('id','box');
			
			if ($("#popup").length != 0) {
				
				$("#popup").css({ opacity:"0.0", display:"block" });
				
			} else {
				
				var popup = $("<div/>").attr('id','popup');
				var headline = $("<h2/>").text("Register");
				var container = $("<div/>").addClass("container"); 
				var form = $("<form/>").attr({ action:'controller/form_handler.php', method:'post' });
				
				var leftdiv = $("<div/>").addClass("left");
				var dl = $("<dl/>");
				createInput("first_name","First name").appendTo(dl);
				createInput("last_name","Last name").appendTo(dl);
				createInput("email","E-Mail").appendTo(dl);
				createInput("skype","Skype").appendTo(dl);						
				createInput("password","Password").appendTo(dl);		
				createInput("password2","Retype password").appendTo(dl);		
				dl.appendTo(leftdiv);
				
				var rightdiv = $("<div/>").addClass("right");
				var dl = $("<dl/>");
				createInput("alias","Username").appendTo(dl);
				createInput("country","Country").appendTo(dl);
				createInput("city","City").appendTo(dl);				
				createInput("birthdate","Birthdate").appendTo(dl);
				dl.appendTo(rightdiv);
				
				var hidden = $("<input/>").attr({ type:'hidden', id:'_get_function', name:'_get_function', value:'add_user' });
				var button = $("<input/>").attr({ type:'Submit', id:'button', value:'Skicka' });
				
				button.click(function(){
					validation=true;
					$("#popup input").each(function (i){						
						if (!validate($(this))) {
							validation=false;
						}
					});					
					if (!validation) {
						return false;
					}
				});
				
				var footer = $("<div/>").addClass("footer"); 
				footer.append(hidden,button);				

				container.append(leftdiv,rightdiv,footer);
				container.appendTo(form);
				form.appendTo(popup);
				
				headline.prependTo(popup);
			}
			
			box.click(function(){
				$("#popup").animate({ opacity:"0.0"}, 200, function(){ $(this).hide(); });		
				$(this).animate({ opacity:"0.0"}, 200, function(){ $(this).remove(); });			
			});

			$("body").prepend(box);

			$("body #box").animate({opacity:"0.7"}, 1000,
				function(){
					$("body").prepend(popup);
					$("#popup").css({ top:'50%',left:'50%',margin:'-'+($('#popup').height() / 2)+'px 0 0 -'+($('#popup').width() / 2)+'px' });
					$("#popup").animate({ opacity:"1" });
				});			
  		  	event.preventDefault();
			return false;
		});
	
		//******************************
		//*** Joina ett spel ***
		//******************************
		
		$(".comingGameList").each(function (i) {
			var game_id = $(this).children().attr({'name':game_id}).val();
			
			$(this).children(".comingGameListJoinButton").click(function(event){
				
				var box = $("<div/>").attr('id','box');

					var popup = $("<div/>").attr('id','popup');
					var headline = $("<h2/>");
					var game_info = $("<h3/>");
					var container = $("<div/>").addClass("popup_container");
					var form = $("<form/>").attr({ action:'controller/form_handler.php', method:'post' });
					
					var centerdiv = $("<div/>").addClass("center");
					var dl = $("<dl/>");
							    	
			    	$.post("controller/game_info.php?func=availableCountrys", { 'game_id':game_id }, function(data){ 	//Kör AJAX funtionen POST med JQUERY

			    		var taken_countrys = $("<dl/>").attr({ id:'taken_countrys'});
			    		
			    		var label_avalable_contrys = $("<dt>").attr({ htmlFor:'country'}).text("Select your contry");
			    		var avalable_contrys = $("<select/>").attr({ id:'country', name:'country' });
			    		
			    		if (data[0].russia==0) {
			    			avalable_contrys.append($("<option></option>").val("russia").html("Russia"));
			    		} else {
			    			taken_countrys.append($("<dd/>").text(data[0].russia));
			    		}
			    		if (data[0].italy==0) {
			    			avalable_contrys.append($("<option></option>").val("italy").html("Italy")); 
			    		} else {
			    			taken_countrys.append($("<dd/>").text(data[0].italy));
			    		}
			    		if (data[0].germany==0) {
			    			avalable_contrys.append($("<option></option>").val("germany").html("Germany")); 
			    		} else {
			    			taken_countrys.append($("<dd/>").text(data[0].germany));
			    		}
			    		if (data[0].france==0) {
			    			avalable_contrys.append($("<option></option>").val("france").html("France")); 
			    		} else {
			    			taken_countrys.append($("<dd/>").text(data[0].france));
			    		}
			    		if (data[0].austria==0) {
			    			avalable_contrys.append($("<option></option>").val("austria").html("Austria")); 
			    		} else {
			    			taken_countrys.append($("<dd/>").text(data[0].austria));
			    		}
			    		if (data[0].england==0) {
			    			avalable_contrys.append($("<option></option>").val("england").html("England")); 
			    		} else {
			    			taken_countrys.append($("<dd/>").text(data[0].england));
			    		}
			    		if (data[0].turkey==0) {
			    			avalable_contrys.append($("<option></option>").val("turkey").html("Turkey"));
			    		} else {
			    			taken_countrys.append($("<dd/>").text(data[0].turkey));
			    		}

			    		var label_taken_countrys = $("<label>").attr({ htmlFor:'taken_countrys'}).text("Countrys chosen");

			    		label_taken_countrys.append(taken_countrys);		    		
			    		
			    		dl.append(label_taken_countrys);
			    		label_avalable_contrys.append(avalable_contrys);
			    		dl.append(label_avalable_contrys);

			    	},"json");
			    	
					var dl = $("<dl/>");
					game_info.appendTo(centerdiv);
					dl.appendTo(centerdiv);

					$.post("controller/game_info.php?func=gameInfo", { 'game_id':game_id }, function(data){ //Kör AJAX funtionen POST med JQUERY
			    		  if (data[0].password==1) {
			    			createInput("game_password","Password").appendTo(dl);
							dl.appendTo(centerdiv);
			    		  }
			    		  headline.text("Join Game: "+data[0].name );
			    		  game_info.text("Start time:"+data[0].start_time+" Round Time:"+data[0].round_time+"min");
			    	},"json");
					var hidden_input_game_id = $("<input/>").attr({ type:'hidden', id:'game_id', name:'game_id', value:''+game_id+'' });
					var hidden_input_function = $("<input/>").attr({ type:'hidden', id:'_get_function', name:'_get_function', value:'join_game' });
					var button = $("<input/>").attr({ type:'Submit', id:'button', value:'Join' });
					
					var footer = $("<div/>").addClass("footer"); 
					footer.append(hidden_input_game_id,hidden_input_function,button);				
					footer.append();
					
					headline.prependTo(centerdiv);

					container.append(centerdiv,footer);
					container.appendTo(form);
					form.appendTo(popup);
					
				box.click(function(){
					$("#popup").animate({ opacity:"0.0"}, 200, function(){ $(this).hide(); });		
					$(this).animate({ opacity:"0.0"}, 200, function(){ $(this).remove(); });			
				});

				$("body").prepend(box);

				$("body #box").animate({opacity:"0.7"}, 1000,
					function(){
						$("body").prepend(popup);
						$("#popup").css({top:'50%',left:'50%',margin:'-'+($('#popup').height() / 2)+'px 0 0 -'+($('#popup').width() / 2)+'px'});
						$("#popup").animate({opacity:"1"});
					});		
				event.preventDefault();
				return false;
			});
		});		

		//***********************************
		//*** Skapar input till formulär  ***
		//***********************************
		function createInput(name,text) {
			var dt = $("<dt/>");
			var label = $("<label>").attr({
				"for": name}).text(text);
			var dd = $("<dd/>");
			
			if (name=="password" || name=="password2") {
				var input = $("<input/>").attr({ name: ''+name+'', value: "", type:"password", id: ''+name+'' });
			} else if (name=="birthdate") {
				var input = $("<input/>").attr({ name: ''+name+'', value: "YYYY-MM-DD", id: ''+name+'' });
			} else {	
				var input = $("<input/>").attr({ name: ''+name+'', value: "", id: ''+name+'' });
			}
			
		    input.keyup(function() { validate($(this));});
		    input.blur(function() { validate($(this));});
		
			label.appendTo(dt);
			input.appendTo(dd);
			dd.appendTo(dt);
			return dt;
		}

		//******************************
		//*** Form validering ***
		//******************************

	function passedValidation(obj) {
		return obj.css({'border':'solid 2px #557B3E'});
	}
		
	function deniedValidation(obj) {
    	return obj.css({'border':'solid 2px #B27A7B'});
 
	}
		
	function validate(obj) {
        if(obj.attr('id') == 'email')
            var check = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
        else if (obj.attr('id') == "first_name" || obj.attr('id') == "last_name")
            var check = /^[A-Za-z\Å\Ä\Ö\å\ä\ö]{2,40} ?[A-Za-z\Å\Ä\Ö\å\ä\ö]{0,40} ?[A-Za-z\Å\Ä\Ö\å\ä\ö]{0,40}$/;
        else if (obj.attr('id') == "birthdate")
            var check = /^[1-2]{1}[09]{1}[0-9]{2}\-[0-1]{1}[0-9]{1}\-[0-3]{1}[0-9]{1}$/;
        else if (obj.attr('id') == "password" || obj.attr('id') == "password2" || obj.attr('id') == "skype") 
        	var check = "exception";
        else
            var check = undefined;                
            
        if (check != undefined && check != "exception")
        {
            if(check(obj.val()))
            	passedValidation(obj);
            else
            	deniedValidation(obj);
            return check(obj.val());

        }
        else if  (obj.attr('id') == "button") {
        	return true;
        } else if  (obj.attr('id') == "password" || obj.attr('id') == "password2") { //Kollar så att båda lösenorden stämmer
            if(obj.val().length> 4 && (obj.val() == $("#password").val() || obj.val() == $("#password2").val())) {
            	passedValidation(obj);
            	if ($("#password").val()!=$("#password2").val()) {
            		$("#password2").css({'border':'solid 2px #B27A7B' });
            	} else {
                    return true;
            	}
            } else {
            	deniedValidation(obj);
            return false;
            }
            
        } else if  (obj.attr('id') == "skype") { //Skype är inte obligatoriskt, men skriver man in måste det vara längre än 3 bokstäver
            if(obj.val().length == 0 || obj.val().length > 3)
            	passedValidation(obj);
            else
            	deniedValidation(obj);
                
            var output = (obj.val().length> 0) || false;
            return true;
            
        } else	{
            if(obj.val().length > 2)
            	passedValidation(obj);
            else
            	deniedValidation(obj);

            var output = (obj.val().length> 2) || false;
            return true;
        }
        
	}
	

	
	//**********************************************************
	//*** Skicka meddelanden från publika chatten i ett game ***
	//**********************************************************
	
	$("#send").click(function(event) {
		
		var message = $("#message").val().replace(/^\s+|\s+$/g,"");

		if(message.length>1) {
	    	  var chat_room_id = $("#chat_room_id").val(); //var chat_room_id = $(this).siblings('[name=chat_room_id]').val();
	    	  $.post("chat.php?func=send_message", {'message':message,'chat_room_id':chat_room_id }, function(data){},"json");
	    	  $("#message").val("");
			  updateChatRooms();
		}
		  event.preventDefault();
		return false;
	});
	
	
	//*******************************************************
	//*** Funktionalitet för att skapa en ny privat chatt ***
	//*******************************************************
	
	function createPopupChat(with_user_id,with_user_alias) {		
		$.post("chat.php?func=create_room", {'game_id':game_id,'with_user_id':with_user_id,'with_user_alias':with_user_alias },function(data){
	 		var chat_room_id=data.chat_room_id;

			var popupChat = $("<div/>").addClass("chat_popup_container")
				.draggable({ handle:"div.dragable" })
				.attr({ id:"chat_room_id_"+chat_room_id, style:"position:fixed; left:10px; top:10px;" });
			var chat_name = $("<div/>").text(with_user_alias).addClass("dragable");
			
			var invitePlayer = popupChatInvitePlayer(data.chat_room_id);
			var exitRoom = popupChatExitRoom();
			var miniAndMaxi = popupChattMiniAndMaximize(data.chat_room_id);
			
			var chatMessageContainer = $("<div/>").addClass("chat_message_container");
			var chatMessageList = $("<dl/>");
			
			chatMessageContainer.append(chatMessageList);
			
			var chatMessageForm = $("<form/>");

			var chatMessageInput = $("<input/>").attr({ type:"text", id:"message", name:"message" });
			var inputChatRoomId = $("<input/>").attr({ type:"hidden", name:"chat_room_id", value: data.chat_room_id });//KOLLA UPP
			
			var inputSubmit = popupChatSubmitMessage(data.chat_room_id);

			chatMessageForm.append(chatMessageInput,inputChatRoomId,inputSubmit);
			popupChat.append(invitePlayer,miniAndMaxi,exitRoom,chat_name,chatMessageContainer,chatMessageForm);
			$("body").append(popupChat);
			updateChatRooms();
		},"json");
	}

	//****************************************************************************
	//*** Funktionalitet för att skicka ett privat meddelande från privat chat ***
	//****************************************************************************
	
	function popupChatSubmitMessage() {
		var inputSubmit = $("<input/>").attr({ type:"submit", id:"send", value:"skicka", style:"visibility:hidden;" })
			.click( function(event) {
				var message = $(this).siblings("#message").val().replace(/^\s+|\s+$/g,""); //trimmar bort space före och efter.
				if(message.length>1) {					
					var chat_room_id = $(this).siblings('[name=chat_room_id]').val();
					  
					$.post("chat.php?func=send_message", { 'message':message, 'chat_room_id':chat_room_id }, function(data){
						updateChatRooms();
					},"json");
				}
				$(this).siblings("#message").val("");
				event.preventDefault();
				return false;
		});
		return inputSubmit;
	}
	
	//*****************************************************************************************
	//*** Funktionalitet till att få en lista med spelare att bjuda in till en privat chatt ***
	//*****************************************************************************************
	
	function getUserListForPrivateChat(chat_room_id) {
		var userList = $("<ul/>");
		$("#userlist_for_room_id_"+chat_room_id +" li").remove();
		$.post("chat.php?func=get_users_in_game_but_not_in_this_chat", { 'game_id':game_id, 'chat_room_id':chat_room_id }, function(data){ 
			$(data).each(function (i) {
				var userListEachUser = $("<li/>");
				var formUserInChat = $("<form/>").attr({ method:'post' }).addClass("userList");
				var hiddenUserId = $("<input/>").attr({ type:'hidden', value:''+data[i].id+'', name:'user_id' });
				var labelPrivateMessag = $("<label/>").attr({ htmlFor:'invite_to_chat' }).text("Create Private Chat").attr({ style:"display:none"});
				var buttonInvitePlayer = $("<input/>").attr({ type:'submit', value:data[i].alias, name:'invite_to_chat' })
					.click(function(event) {		
						invitePlayer(data[i].id,chat_room_id);
						$(this).parent().parent().remove();
					  	event.preventDefault();
						return false;
					});
			
				formUserInChat.append(hiddenUserId);
				formUserInChat.append(labelPrivateMessag);
				formUserInChat.append(buttonInvitePlayer);
			 	userListEachUser.append(formUserInChat);
			 	
			 	userList.append(userListEachUser);
				
			 });
		},"json");
		return userList;
	}	
	
	//************************************************************************
	//*** Funktionalitet till att lägga till en användare i en privat chat ***
	//************************************************************************
	
	function invitePlayer(user_id,chat_room_id) {
  	  $.post("chat.php?func=invite_player", { 'user_id':user_id, 'chat_room_id':chat_room_id }, function(data){ 	//Kör AJAX funtionen POST med JQUERY
		  updateChatRooms();
	  },"json");
	}
	
	//*********************************
	//*** Exit knapp till popupChat ***
	//*********************************

	function popupChatExitRoom() {
		var exitRoom = $("<img/>").attr({ src: imgurl+"chat_popup_close.png", title: "Exit", alt: "Exit" })
			.addClass("exitRoom")
			.click(function() {
				var chat_room_id = $(this).siblings("form").find('[name=chat_room_id]').val();				
				$.post("chat.php?func=exit_room", { 'chat_room_id':chat_room_id }, function(data){},"json");
				$(this).parent().remove();
			});
		return exitRoom;
	}
	
	//*********************************************************
	//*** Knapp för att  bjuda in spelare till privat chatt ***
	//*********************************************************
	
	function popupChatInvitePlayer(chat_room_id) {
		var show_userlist = false;
		var userListContainer = $("<div/>").attr({ id:"userlist_for_room_id_"+chat_room_id }).addClass("userlist_in_popup").hide();

		var userList = getUserListForPrivateChat(chat_room_id);
		userListContainer.append(userList);

		var invitePlayer = $("<div/>")
			.addClass("invitePlayer")
			.click(function() {
				if (show_userlist==false) {
					$(this).find(".userlist_in_popup").show();
					show_userlist=true;
				} else {
					$(this).find(".userlist_in_popup").hide();
					show_userlist=false;
				}
			});
		invitePlayer.append(userListContainer);		

		return invitePlayer;
	}
 	
	//**********************************************************************
	//*** Funktionalitet till att förminska och förstora en privat chatt ***
	//**********************************************************************
	
	function popupChattMiniAndMaximize(chat_room_id) {
		var minimize = $("<img/>").attr({ src: imgurl+"chat_popup_minimize.png", title: "Minimize", alt: "Minimize" })
			.addClass("minimize")
			.click(function() {				
				var bottom = $(window).height()-23;
		
				var position = $(this).parent().position();
				
				var top_pos = position.top;
				var left_pos = position.left;
		
				var free_tab;
				var to_ending=true;
		
				for (var i=0; i<= bottom_tabs.length;i++) {
					if (bottom_tabs[i] == null && to_ending==true) {
						to_ending = false;
						free_tab=i;	
					}
				}
				
				// Animering längst ner i fönstert
				$(this).parent().animate({"left": free_tab*200+"px","top": bottom+"px"}, "slow"); //200 är bredden på varje privat chatt
				$(this).attr({ style:"display:none" });
				$("#chat_room_id_"+chat_room_id+" .exitRoom").attr({ style:"display:none;" });
				$("#chat_room_id_"+chat_room_id+" .invitePlayer").attr({ style:"display:none;" });
				$(this).parent().draggable( "option", "disabled", true );
		
				var to_ending=true;
				
				for (var i=0; i<= bottom_tabs.length;i++) {
					if (bottom_tabs[i] == null && to_ending==true) {
						to_ending = false;
						bottom_tabs[i] = chat_room_id;
					}
				}
				
				var first_time=true;
				var maximize = $("<img/>").attr({ src: imgurl+"chat_popup_maximize.png", title: "Maximize", alt: "Maximize" })
					.addClass("maximize")
					.click(function() {	
						$(this).parent().animate({"left": left_pos+"px","top": top_pos+"px"}, "slow");
						$(this).attr({ style:"display:none;" });
						$("#chat_room_id_"+chat_room_id+" .minimize").attr({ style:"display:block;" });
						$("#chat_room_id_"+chat_room_id+" .exitRoom").attr({ style:"display:block;" });
						$("#chat_room_id_"+chat_room_id+" .invitePlayer").attr({ style:"display:block;" });
						$(this).parent().find(".newMessage").remove();
						$(this).parent().draggable( "option", "disabled", false );
			
						if (first_time==true) {
							first_time=false;
						}
						
						$(bottom_tabs).each(function(i){
							if (bottom_tabs[i] == chat_room_id)
								bottom_tabs[i] = null;
						});							
			         });
	
				$("#chat_room_id_"+chat_room_id).prepend(maximize);
				maximize.attr({ style:"display:block;" });
			});
		return minimize;
	}
	
	//**************************************************************
	//*** Huvudontroller och funktioner för att allt ska fungera ***
	//**************************************************************

	var last_post_id=0;
	var bottom_tabs = [];
	var first_update=1;
	
	//Kontrollerar om man är i Game Lobby
	if ($("#room_and_game_information").size()) {	
		game_id=$("#game_id").val();
		chat_room_id=$("#chat_room_id").val();
		updateTimer();
		var last_post_id=0;
		updateUserLists();
	}	
	
	// Kontrollerar om man är inne i ett Game, aktiverar chatten och skapar en lista med användarna i gamet	
	if ($("#countryStats").size()) {
		updateGameUserList();
		$(".chatRoomInGame").draggable({ handle:"div.dragableMainchat" });

	};
	
	
	function updateTimer() { //Hur ofta chatten ska hämta meddekanden
	   updateChatRooms();
	   setTimeout(updateTimer, 5000);
	} 
	
	$("#chat_form").click(function(event){	// Stoppar att sidan laddas om när man skickar ett meddelande i huvudchatten.
		event.preventDefault();
		return false;
	});

	//***************************************************************************
	//*** Funktionalitet till att uppdatera användarna som är i publika rummet ***
	//****************************************************************************
	
	function updateUserLists() {
		$("#users_in_chat_"+game_id +" li").remove();
		$.post("chat.php?func=get_users_in_game", { 'game_id':game_id, 'chat_room_id':chat_room_id }, function(data){ 
			$(data).each(function (i) {
				var userList = $("<li/>");
				var formUserInChat = $("<form/>").attr({ id:'user_in_chat'+'',method:'post' }).addClass("chat_userlist");
				var hiddenUserId = $("<input/>").attr({ type:'hidden', value:''+data[i].id+'', name:'user_id' });
				var labelPrivateMessag = $("<label/>").attr({ htmlFor:'create_private_chat' }).text("Create Private Chat").attr({ style:"display:none"});
				var buttonPrivateMessage = $("<input/>").attr({ type:'submit', value:data[i].alias, name:'create_private_chat' })
					.click(function(event) {	
						if (data[i].id!=$("#user_id").val()) { createPopupChat(data[i].id,data[i].alias); };
					  	event.preventDefault();
						return false;
					});
				var containerGoToUserPage = $("<div/>");
				var goToUserPage = $("<a/>").attr({ href:"index.php?p=userinfo&u="+data[i].id }).text("P");
				goToUserPage.appendTo(containerGoToUserPage);				
				var user = $("<li/>").append($('<a href="?create_chat_with_user='+data[i].id+'">'+data[i].alias+'</a>'));
			 	var chat_room_id = data[i].chat_room_id;
			 	
			 	formUserInChat.append(hiddenUserId);
			 	formUserInChat.append(labelPrivateMessag);
			 	formUserInChat.append(buttonPrivateMessage,containerGoToUserPage);
			 	userList.append(formUserInChat);
				$("#users_in_chat_"+chat_room_id +" ul").append(userList);
			 });
		},"json");
	}
	
	//****************************************************************************
	//*** Hämtar hem alla nya meddelanden och spar nya rum om dessa inte finns ***
	//****************************************************************************
	
	function updateChatRooms() {
		var chat_room_ids = [];
		
		if($(".chat_room_fixed").attr('id')) {
			chat_room_ids.push($(".chat_room_fixed").attr('id'));
		} else if ($(".chatRoomInGame").attr('id')){
			chat_room_ids.push($(".chatRoomInGame").attr('id'));
		}
		
		$(".chat_popup_container").each(function (i) {
			chat_room_ids.push($(this).attr('id'));
		});
		
		function is_in_array(array_with_ids,check_id) {	
			var return_value=false;
			$(array_with_ids).each(function (i) {
				if (parseInt(array_with_ids[i].substring(13))==parseInt(check_id)) {
					return_value = true;
				}
			});
			return return_value;
		}

		$.post("chat.php?func=update_messages", { 'last_post_id':last_post_id, 'game_id':game_id }, function(data){
			$(data).each(function (i) {
		 		var chat_room_id=data[i]['chat_room_id'];
				var alias = $("<dt/>").text(data[i].alias);
			 	var message = $("<dd/>").text(data[i].message);
			 	var timestamp = $("<div/>").text(data[i].timestamp);
			 	
				var room_data=data;
				
				if (!(is_in_array(chat_room_ids,data[i]['chat_room_id']))) { //Om rummet inte finns som meddelandet ska liggas i så skapas det
					var game_id = $("#game_id").val();
					$.post("chat.php?func=get_room_info", { 'game_id':game_id,'chat_room_id':chat_room_id }, function(data){ 
						var popupChat = $("<div/>")
							.addClass("chat_popup_container")
							.draggable({ handle:"div.dragable" })
							.attr({ id:"chat_room_id_"+chat_room_id, style:"position:fixed;" });
	
						var chatName = $("<div/>")
							.text(data[0].name)
							.addClass("dragable");
						
						var invitePlayer = popupChatInvitePlayer(chat_room_id);
						var exitRoom = popupChatExitRoom();				
						var miniAndMaxi = popupChattMiniAndMaximize(chat_room_id);

						var chatMessageContainer = $("<div/>").addClass("chat_message_container");
						var chatMessageList = $("<dl/>");
						
						//Skriver ut alla tidigare meddelanden
						$(room_data).each(function (i) {
							if (room_data[i].chat_room_id==chat_room_id) {
								var alias = $("<dt/>").text(room_data[i].alias);
							 	var message = $("<dd/>").text(room_data[i].message);
							 	var timestamp = $("<div/>").text(room_data[i].timestamp);
							 	chatMessageList.append(timestamp,alias,message);
							}
						});
						
						chatMessageContainer.append(chatMessageList);
						
						var chatMessageForm = $("<form/>");
						
						var chatMessageInput = $("<input/>").attr({ type: "text", id:"message", name:"message"	});
						var inputChatRoomId = $("<input/>").attr({ type: "hidden", name:"chat_room_id", value: chat_room_id }); //id:"chat_room_id",  chat_room_id ---BORT

						var inputSubmit = popupChatSubmitMessage(chat_room_id);
						
						chatMessageForm.append(chatMessageInput,inputChatRoomId,inputSubmit);
						popupChat.append(invitePlayer,miniAndMaxi,chatName,exitRoom,chatMessageContainer,chatMessageForm);
						
						$("#container").append(popupChat);
					},"json");

					chat_room_ids.push("chat_room_id_"+data[i].chat_room_id);
				} else {
					$("#chat_room_id_"+chat_room_id +" .chat_message_container dl").append(timestamp,alias,message);
					$("#chat_room_id_"+chat_room_id +" .chat_message_container").scrollTop(99999); //om det är en popup
					$("#chat_room_id_"+chat_room_id +" .chat_message_container dl").scrollTop(99999); //om det är fasta chatten
					
					//Om det inte är chat_room_fixeds id då så kolla igenom om det är en popup som är förmiskad för att "blinka" och tala om att någon har skrivit ett nytt meddelande.
					if ($(".chat_room_fixed").attr('id')!=$("#chat_room_id_"+chat_room_id).attr('id') && $("#chat_room_id_"+chat_room_id).attr('id')) {
						var temp=$("#chat_room_id_"+chat_room_id).attr('id').substr(13);
						
						for (var j=0; j<= bottom_tabs.length;j++) {
							if (bottom_tabs[j] == temp) {
								$("#chat_room_id_"+chat_room_id).effect( 'pulsate','','slow');
								
								var newMessage = $("<img/>").attr({ src: imgurl+"chat_popup_new_message.png", title: "New message", alt: "New message" })
									.addClass("newMessage");
								$("#chat_room_id_"+chat_room_id).append(newMessage);
							}
						}
					} else if ($(".chat_room_fixed").attr('id')==$("#chat_room_id_"+chat_room_id).attr('id') && first_update==0) { //first update vill inte fungera
						message = data[i].message;
						if (message.match("has entered the room")) { //Uppdaterar userlist för huvudchatten om någon ny kommerin (denna funktion finns ej för popup chatten)
							updateUserLists();
						}
					}
	
					last_post_id=(data[i].count);
					}
				});
			first_update=0;
		},"json");
	}
	
	//*********************************************************************************************************
	//*** Funktionalitet för att skapa användarlistan inne i ett game så man även kan skapa privata chatter ***
	//*********************************************************************************************************
	
	function updateGameUserList() {
		$.post("controller/game_info.php?func=gameUserList", { 'game_id':game_id }, function(data){ 
			$(data).each(function (i) {
				var userList = $("<li/>").attr({ id:data[i].land+'-stats'});
				var formUserInChat = $("<form/>").attr({ id:'user_in_chat'+'',method:'post' }).addClass("gameChatUserList");
				var hiddenUserId = $("<input/>").attr({ type:'hidden', value:''+data[i].id+'', name:'user_id' });
				var labelPrivateMessag = $("<label/>").attr({ htmlFor:'create_private_chat' }).text("Create Private Chat").attr({ style:"display:none"});
					var buttonPrivateMessage = $("<input/>").attr({ type:'submit', value:"("+data[i].nations+")"+data[i].alias, name:'create_private_chat',style:"z-index:9999" })
						.click(function(event) {		
							if (data[i].id!=$("#user_id").val()) { createPopupChat(data[i].id,data[i].alias); };
						  	event.preventDefault();
							return false;
						});
			 	var chat_room_id = data[i].chat_room_id;
			 	
			 	formUserInChat.append(hiddenUserId);
			 	formUserInChat.append(labelPrivateMessag);
			 	formUserInChat.append(buttonPrivateMessage);//div
			 	userList.append(formUserInChat);
				$("#countryStats" +" ul").append(userList);
			 });
		},"json");
	}
});